package leaf.cloud.common.massage.service;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import leaf.cloud.common.massage.entity.MassageMain;
import leaf.cloud.common.massage.entity.WechatDepartment;
import leaf.cloud.common.massage.entity.WechatPersonnel;
import leaf.cloud.common.massage.entity.WechatResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 企业微信服务
 *
 * @author yzh
 * @since 2022/7/1 15:15
 */
@Service("wechatService")
@RefreshScope
@Slf4j
public class WechatServiceImpl {

    private final String authorizeURL = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=CORPID&redirect_uri=REDIRECT_URI&response_type=code&scope=snsapi_base&state=STATE&agentid=AGENTID#wechat_redirect";
    private final String departmentListURL = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=%s&id=%s";
    private final String personnelListURL = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token=%s&department_id=%s&fetch_child=1";
    private final String toOpenIdURL = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=%s";
    private final String sendURL = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=";
    private final String sendAppChatURL = "https://qyapi.weixin.qq.com/cgi-bin/appchat/send?access_token=";
    private final String getUserInfoURL = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=%s&code=%s";
    //关联企业id
    private final String linkedCode = "whc8a7dfa5cc50b57e/";

    private WechatResult resultToClass(String result) {
        return JSONObject.parseObject(result, WechatResult.class);
    }


    public String codeToUserId(String token, String code) {
        JSONObject result = JSONObject.parseObject(HttpUtil.get(String.format(getUserInfoURL, token, code)));
        return result.getString("UserId");
    }


    public String userIdToOpenId(String token, String userId) {//new HashMap<String,String>(){{put("userid",userId);}}
        String result = HttpUtil.post(String.format(toOpenIdURL, token), String.format("{\"userid\": \"%s\"}", userId));
        return JSONObject.parseObject(result).getString("openid");
    }


    public List<WechatDepartment> getDepartmentList(String token, String departmentId) {
        String result = HttpUtil.get(String.format(departmentListURL, token, departmentId));
        return resultToClass(result).getDepartment();
    }


    public List<WechatDepartment> getLinkedDepartmentList(String token, String departmentId) {
        String result = HttpUtil.post("https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/department/list?access_token=" + token
                , "{\"department_id\": \"" + linkedCode + departmentId + "\"}");
        JSONObject jsonObject = JSONObject.parseObject(result);
        JSONArray array = jsonObject.getJSONArray("department_list");
        return array.stream().map(o -> {
            JSONObject object = JSONObject.parseObject(o.toString());
            return new WechatDepartment(object.getIntValue("department_id")
                    , object.getString("department_name")
                    , object.getIntValue("parentid")
                    , object.getLongValue("order")
                    , CollUtil.newArrayList());
        }).sorted(Comparator.comparing(WechatDepartment::getId)).collect(Collectors.toList());
    }


    public List<WechatPersonnel> getPersonnelByDepartmentId(String token, String departmentId) {
        String result = HttpUtil.get(String.format(personnelListURL, token, departmentId));
        return resultToClass(result).getUserlist();
    }


    public List<WechatPersonnel> getLinkedPersonnelByDepartmentId(String token, String departmentId) {
        String result = HttpUtil.post("https://qyapi.weixin.qq.com/cgi-bin/linkedcorp/user/list?access_token=" + token
                , "{\"department_id\": \"" + linkedCode + departmentId + "\"}");
        List<WechatPersonnel> userList = resultToClass(result).getUserlist();
        if (CollUtil.isNotEmpty(userList)) {
            userList.forEach(o -> o.setMain_department(Long.parseLong(o.getDepartment().get(0).substring(linkedCode.length()))));
        }
        return userList;
    }


    /**
     * 发送应用消息
     *
     * @param token   token
     * @param message 消息
     * @return 结果
     */
    public WechatResult sendMessage(String token, MassageMain message) {
        String result = HttpUtil.post(sendURL + token, JSONObject.toJSONString(message));
        log.info(result);
        return resultToClass(result);
    }

    /**
     * 发送群消息
     *
     * @param token   token
     * @param message 消息
     * @return 结果
     */
    public WechatResult sendAppChatMessage(String token, MassageMain message) {
        String result = HttpUtil.post(sendAppChatURL + token, JSONObject.toJSONString(message));
        log.info(result);
        return resultToClass(result);
    }

}
